package io.dirac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.dirac.dto.OrderListDto;
import io.dirac.entity.OrderDetail;
import io.dirac.entity.OrderSurvey;
import io.dirac.entity.Product;
import io.dirac.mapper.OrderDetailMapper;
import io.dirac.mapper.OrderSurveyMapper;
import io.dirac.mapper.ProductMapper;
import io.dirac.service.OrderListDtoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrderListDtoServiceImpl implements OrderListDtoService {

    @Autowired
    private OrderSurveyMapper orderSurveyMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public List<OrderListDto> getBatchByUserId(Long userId) {
        List<OrderListDto> orderListDtos = new ArrayList<>();

        QueryWrapper<OrderSurvey> orderSurveyQueryWrapper = new QueryWrapper<>();
        orderSurveyQueryWrapper.eq("user_id", userId);
        orderSurveyQueryWrapper.orderByDesc("gmt_created");
        List<OrderSurvey> orderSurveys =  orderSurveyMapper.selectList(orderSurveyQueryWrapper);
        for (OrderSurvey orderSurvey : orderSurveys) {
            QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
            orderDetailQueryWrapper.eq("order_id", orderSurvey.getId());
            List<OrderDetail> orderDetails =  orderDetailMapper.selectList(orderDetailQueryWrapper);
            for (OrderDetail orderDetail : orderDetails) {
                OrderListDto orderListDto = new OrderListDto();
                orderListDto.setOrderId(orderSurvey.getId());
                orderListDto.setUserName(orderSurvey.getUserName());
                Product product = productMapper.selectById(orderDetail.getProductId());
                orderListDto.setProductName(product.getName());
                orderListDto.setProductImgPath(product.getImgPath());
                orderListDto.setProductPrice(product.getPrice());
                orderListDto.setPurchaseAmount(orderDetail.getPurchaseQuantity());
                orderListDto.setProductStock(product.getStock());
                orderListDto.setOrderStatus(orderSurvey.getStatus());
                orderListDtos.add(orderListDto);
            }
        }
        return orderListDtos;
    }
}
